package com.hk.Mgr.web.controller;

import com.hk.Mgr.web.message.sys.AppGestureCipherRes;
import com.hk.Mgr.web.message.sys.GetCipherStateRes;
import com.hk.Mgr.web.message.sys.SysUserPhoneReq;
import com.hk.Mgr.web.message.sys.SysUserRes;
import com.hk.app.utils.SendMsgCilent;
import com.hk.base.ResponseBase;
import com.hk.commons.*;
import com.hk.commons.entity.Answer;
import com.hk.commons.entity.Parameter;
import com.hk.commons.entity.pay.FM;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.MsgTypeConstants;
import com.hk.commons.utils.sys.DateHelper;
import com.hk.commons.utils.sys.MD5Crypter;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.commons.vo.CheckInfo;
import com.hk.res.UserRes;
import com.hk.service.IOrganization;
import com.hk.service.IOrganization_New;
import com.hk.service.IPush;
import com.hk.service.kyc.ICard;
import com.hk.service.kyc.ICoupon;
import com.hk.service.order.IParameter;
import com.hk.service.order.IPayment;
import com.hk.service.sys.IAnswer;
import com.hk.service.sys.ISysUser;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/userInfo")
public class UserCtr {

	private Logger logger = LoggerFactory.getLogger(UserCtr.class);

	@Autowired
	private ISysUser userImpl;

	@Autowired
	private IPayment paymentImpl;

	@Autowired
	private SendMsgCilent sendMsgCilent;

	@Autowired
	private IPush pushService;

	@Autowired
	private IAnswer answerService;

	@Autowired
	public YingmiApiUtils utils;
	
	@Autowired
	private ICoupon couponService;

	@Autowired
	private IOrganization_New orgNewService;


	@Value("${fy.Secret}")
	private String fySecret;

	@Value("${fy.mchntCd}")
	private String fyMchntCd;

	@Value("${fy.scheme}")
	private String scheme;

	@Value("${fy.valiFour}")
	private String realUrl;

	@Value("${fy.validateCardPath}")
	private String path;

	@Value("${fy.getBankPath}")
	private String getBankpath;

	@Value("${webServer.baseUrl}")
	private String webUrl;

	@Autowired
	private IParameter parmService;
	
	/*
	@Autowired
	private IUserCard userCardService;
	*/
	
	@Autowired
	private ICard cardService;

	/*
	 * @Autowired private IFundInfo_Yimi fundInfo;
	 */

	private RestTemplate template = new RestTemplate();

	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ResponseBase<SysUserRes> login(@RequestBody UserRes req) {

		logger.info("userName:{} , msgCode:{}", req.getName(), req.getMsgCode());
		ResponseBase<SysUserRes> rb = new ResponseBase<>();
		String phoneWhiteList = "13556806196,18902212310";
		HqlFilter hqlFilter = new HqlFilter();
		if (StringUtils.isNotEmpty(req.getName())) {
			String msgCode = RedisCilent
					.getString(CacheConstants.MOBLIE_MSG_CODE + req.getName());
			String company = RedisCilent
					.getString(CacheConstants.MOBLIE_MSG_CODE + req.getName()
							+ "company");
			hqlFilter.addEQFilter("name", req.getName().trim());
			hqlFilter.addEQFilter("closeAccount",0); //只有末销户的用户才能登录-2.7.6

			List<SysUser> list = userImpl.findByFilter(hqlFilter);

			if (list.size() == 0) {
				logger.info("login 此用户不存在 name = {} ",req.getName());
				rb.setMsg("此用户不存在");
				rb.setResultCode(ResultCode.USER_NOT_EXIST.getCode());
				return rb;
			}

			SysUser loginUser = list.get(0);
			SysUserRes sresp = new SysUserRes();
			// add by Sam 2016/07/22 增加token

			switch (req.getLoginType()) {
			case 1:// 验证码登陆
				if (StringUtils.isNotEmpty(req.getMsgCode())) {
					if (phoneWhiteList.contains(req.getName())
							|| ("YIJIA".equals(company) && (StringUtils
									.equalsIgnoreCase(msgCode, req.getMsgCode())))
							|| ("JIGUANG".equals(company) && (validateJG(
									req.getMsgCode(), req.getName(), 0)))) {
						ReqToModelHelper.copyReqValueToModel(loginUser, sresp);
						String token = RandomStringUtils.randomAlphanumeric(64);
						sresp.setToken(token);
						RedisCilent.setString(CacheConstants.UserLog_Token
								+ loginUser.getId(), token, 604800);
						// 短信验证登录成功
						// 短信验证登录如果成功，且mobileId 不相同时，更改用户的mobileId
						if (StringHelper.isEmpty(loginUser.getMobileId())
								|| (!loginUser.getMobileId().equals(
										req.getMobileId()))) {
							if (StringHelper
									.isNotEmpty(loginUser.getMobileId())) {
								Answer an = answerService
										.getByMobileId(loginUser.getMobileId());
								if (an != null) {
									an.setMobileId(req.getMobileId());
									answerService.update(an);
								}
							}
							loginUser.setMobileId(req.getMobileId());
							userImpl.update(loginUser);
							Answer nowMobileAnswer = answerService
									.getByMobileId(req.getMobileId());
							if (nowMobileAnswer != null) {
								answerService.delete(nowMobileAnswer.getId());
							}
						}
						sresp.setMobileId(req.getMobileId());

						rb.setResult(sresp);
						RedisCilent.delKey(CacheConstants.MOBLIE_MSG_CODE
								+ req.getName() + "company");
						RedisCilent.delKey(CacheConstants.MOBLIE_MSG_CODE
								+ req.getName());
					} else {
						logger.info("login 验证码错误 name={},msgCode={}",req.getName(),req.getMsgCode());
						rb.setMsg("验证码错误，请输入正确的验证码.");
						rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
					}
				} else {
					rb.setMsg("验证码不能为空，请输入正确的验证码.");
					rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
				}

				break;

			case 2:// 密码登陆
				if (list.get(0).getPwd().equalsIgnoreCase(req.getPwd())) {// 密码登陆如果换手机了，在新手机上第一次都要验证码登陆。更安全，发送到你自己的手机
					// 此时账户和密码相同,再判断UUID 是否相同
					// SysUser loginUser = list.get(0);
					// 如果手机唯一识别码和数据库中用户的唯一识别码相同
					ReqToModelHelper.copyReqValueToModel(loginUser, sresp);
					String token = RandomStringUtils.randomAlphanumeric(64);

					if (StringHelper.isNotEmpty(loginUser.getMobileId())
							&& StringHelper.isNotEmpty(loginUser.getMobileId())
							&& loginUser.getMobileId()
									.equals(req.getMobileId())) {
						sresp.setToken(token);
						RedisCilent.setString(CacheConstants.UserLog_Token
								+ loginUser.getId(), token, 604800);
						rb.setResult(sresp);
						// 判断是否是测试员
					} else if (req.getName().equalsIgnoreCase("13411112222")
							|| req.getName().equalsIgnoreCase("18988888888")) {
						sresp.setToken(token);
						RedisCilent.setString(CacheConstants.UserLog_Token
								+ loginUser.getId(), token, 604800);
						rb.setResult(sresp);
						logger.info("The login user is the tester, and will login succ.");
					} else {
						rb.setMsg(ResultCode.PHONE_CHANGE.getMsg());
						rb.setResultCode(ResultCode.PHONE_CHANGE.getCode());
					}

				} else {
					logger.info("login 账号或密码错误 name={}",req.getName());
					rb.setMsg("账号或密码错误，请重新输入.");
					rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
				}
				break;
			}

		} else {
			logger.info("login 用户名与密码有空");
			rb.setMsg("用户名与密码不能为空，请重新输入.");
			rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
		}
		// logger.info("adhfjsf{}", new JSONObject(rb));
		return rb;

	}

	private boolean validateJG(String msgCode, String mobile, int status) {
		logger.info("进入极光验证短信");
		Map<String, String> resultJgMap = sendMsgCilent.validate(msgCode, mobile, 0);
		logger.info("极光验证mobile={},返回结果={}", mobile, new JSONObject(resultJgMap));
		if ("-1111".equals(resultJgMap.get("code"))) {
			return false;
		} else {
			return true;
		}
	}

	@ResponseBody
	@RequestMapping(value = "/getMsgCode", method = RequestMethod.GET)
	public ResponseBase<String> getMsgCode(@RequestParam String mobile,
			String ifJG, String channel) {// 1 IOS 2 android
		ResponseBase<String> rb = new ResponseBase<>();
		Random random = new Random();
		String content = "";
		for (int i = 0; i < 6; i++) {
			content += random.nextInt(10);
		}

		Map<String, String> resultMap = sendMsgCilent.senMsgRoute(mobile,
				content, ifJG, channel);
		boolean t = Boolean.valueOf(resultMap.get("result"));
		logger.info("after getMsgCode  moblie: {} , send status:{}", mobile, t);
		if (t) {
			String company = resultMap.get("company");
			RedisCilent.setString(CacheConstants.MOBLIE_MSG_CODE + mobile
					+ "company", company, 300);
			if ("YIJIA".equals(company)) {
				RedisCilent.setString(CacheConstants.MOBLIE_MSG_CODE + mobile,
						content, 1000);
			}

			rb.setResult(content);
		} else {
			rb.setMsg("短信发送失败");
			rb.setResultCode(ResultCode.FAILED.getCode());
		}

		return rb;

	}


	@ResponseBody
	@RequestMapping(value = "/registPreCheck", method = RequestMethod.GET)
	public ResponseBase<Map<String, Object>> registPreCheck() {
		ResponseBase<Map<String, Object>> resp = new ResponseBase<Map<String, Object>>();
		try {
			Map<String, Object> resultMap = new TreeMap<String, Object>(
					new Comparator<String>() {
						public int compare(String obj1, String obj2) {
							// 降序排序
							return obj2.compareTo(obj1);
						}
					});

			Boolean checkLimitResult = false;
			resultMap.put("checkResult", false);

			Parameter parm = parmService.getByName(ConstantParm.REGIST_CODE_LIMIT);

			if (parm != null && StringHelper.isNotEmpty(parm.getValue01()) && StringHelper.isNotEmpty(parm.getValue02()) && StringHelper.isNotEmpty(parm.getValue03())) {
				Long startTime = DateHelper.stringToDate(parm.getValue02()).getTime();

				Long endTime = DateHelper.stringToDate(parm.getValue03()).getTime();

				Long currentTime = System.currentTimeMillis();

				if (parm.getValue01().equals("1") && startTime.compareTo(currentTime) == -1 && endTime.compareTo(currentTime) == 1) {
					resultMap.put("checkResult", true);
				}
			}

			Parameter limitParm = parmService.getByName(ConstantParm.REGIST_CODE_PROMPT_LIMIT_TRUE);

			Parameter noLimitParm = parmService.getByName(ConstantParm.REGIST_CODE_PROMPT_LIMIT_FALSE);

			if (limitParm == null || noLimitParm == null) {
				logger.error("参数设置错误，请检查参数设置！");
				return resp;
			}

			resultMap.put("limitInputPromot", limitParm.getValue01());
			resultMap.put("limitButton", limitParm.getValue02());
			resultMap.put("limitMsgPromot", limitParm.getValue03());

			resultMap.put("noLimitInputPromot", noLimitParm.getValue01());
			resultMap.put("noLimitButtonLeft", noLimitParm.getValue02());
			resultMap.put("noLimitButtonRight", noLimitParm.getValue03());
			resultMap.put("noLimitMsgPromot", noLimitParm.getValue04());

			resp.setResult(resultMap);
			resp.setResultCode(ResultCode.SUCC.getCode());
		}catch (Exception e){
			logger.info("registPreCheck  error ----------->, e={}", e);
		}

		return resp;

	}

	//新的接口，推荐码前置
	@ResponseBody
	@RequestMapping(value = "/registerCheck01", method = RequestMethod.POST)
	public ResponseBase<Boolean> getRegistCode(@RequestBody UserRes res) {
		ResponseBase<Boolean> rb = new ResponseBase<>();


		logger.info("registerCheck01 注册registerUser MsgCode:{} , Name:{} , RecommendCode:{}", res.getMsgCode(), res.getName(), res.getRecommendCode());

		String phoneNum = res.getName();
		String msgCode = res.getMsgCode();

		//判断输入参数是否完整
		if (StringHelper.isEmpty(phoneNum) || StringHelper.isEmpty(msgCode)) {
			rb.setMsg("校验失败，手机号或验证码为空！");
			rb.setResultCode(ResultCode.FAILED.getCode());
			return rb;
		}

		CheckInfo checkInfo = checkMsgCode(res.getName(), res.getMsgCode());

		//判断推荐码是否正确
		if (checkInfo.getResult() == false) {
			rb.setMsg(checkInfo.getResultMsg());
			rb.setResultCode(ResultCode.FAILED.getCode());
			return rb;
		}

		SysUser user = userImpl.getByPhoneNum(phoneNum);

		//判断用户是否已存在
		if (user != null) {
			logger.info("registerCheck01-用户已存在 phone={}",phoneNum);
			rb.setMsg("用户已存在");
			rb.setResultCode(ResultCode.FAILED.getCode());
			return rb;
		}


		Boolean needInputCode = ifNeedInputCode();

		if (needInputCode) {
			String recommendCode = res.getRecommendCode();
			if (StringHelper.isEmpty(recommendCode)) {
				rb.setMsg("亲，别忘了填写推荐码哦！");
				rb.setResultCode(ResultCode.FAILED.getCode());
				logger.info("registerCheck01 needInputCode={}, recommendCode={}", needInputCode, recommendCode);
				return rb;
			}

			SysUser finUser = userImpl.getByPhoneNum(res.getRecommendCode());
			if (finUser == null || finUser.getIsInside() == null || finUser.getIsInside() != 1) {
				logger.info("registerCheck01 没有找到这位理财师! recommendCode = {}",res.getRecommendCode());
				rb.setMsg("没有找到这位理财师！");
				rb.setResultCode(ResultCode.FAILED.getCode());
				return rb;
			}
		}
        rb.setResult(true);
        rb.setResultCode(ResultCode.SUCC.getCode());
        return rb;
	}


    //新的接口，推荐码前置接口02
    @ResponseBody
    @RequestMapping(value = "/registerCheck02", method = RequestMethod.POST)
    public ResponseBase<SysUser> registerCheck02(@RequestBody UserRes res) {
        ResponseBase<SysUser> rb = new ResponseBase<>();


        logger.info("registerCheck02- 注册registerUser MsgCode:{} , Name:{} , RecommendCode:{}", res.getMsgCode(), res.getName(), res.getRecommendCode());

        String phoneNum = res.getName();
        Integer mobileType = res.getMobileType();
		String mobileId = res.getMobileId();
        String pwd = res.getPwd();
		String recommendCode = res.getRecommendCode();

        //判断输入参数是否完整
        if (StringHelper.isEmpty(phoneNum) || StringHelper.isEmpty(mobileId) || StringHelper.isEmpty(pwd) ) {
            rb.setMsg("校验失败，部分参数为空！");
            rb.setResultCode(ResultCode.FAILED.getCode());
            return rb;
        }

        SysUser user = userImpl.getByPhoneNum(phoneNum);

        //判断用户是否已存在
        if (user != null) {
        	logger.info("registerCheck02 用户已存在 phone = {}",phoneNum);
            rb.setMsg("用户已存在");
            rb.setResultCode(ResultCode.FAILED.getCode());
            return rb;
        }

		user = new SysUser();
		user.setName(phoneNum);
        if (StringUtils.isNotEmpty(recommendCode)) {
            user.setRecommendCode(recommendCode);
            user.setRecommendId(null);

            // 给用户添加渠道信息
            SysUser finUser = userImpl.getByPhoneNum(res.getRecommendCode());
            if(finUser != null) {
				user.setChannel(finUser.getChannel());

				//如果推荐用户是理财师
				if(finUser.getIsInside() == 1){
					user.setOrgId(finUser.getOrgId());
					user.setRecommendId(finUser.getId());
				}else{
					Integer orgId = orgNewService.getLatestWuZhu(finUser.getOrgId());
					user.setOrgId(orgId);
					user.setRecommendId(null);
				}
            }else {
                user.setChannel(getChannelWangluo());
                user.setOrgId(getDepWuzhu());
            }

        } else {
            user.setRecommendCode(null);
            user.setRecommendId(null);
            user.setChannel(getChannelWangluo());
            user.setOrgId(getDepWuzhu());
        }

        user.setPwd(pwd);
        user.setMobileId(res.getMobileId());
        user.setMobileType(res.getMobileType());

        Long id = userImpl.add(user);
        SysUser resUser = null;
        if (id != null) {
        	logger.info("registerCheck02 注册成功 name={}",phoneNum);
            resUser = userImpl.findById(id);
            rb.setMsg("注册成功");
            rb.setResultCode(ResultCode.SUCC.getCode());
            rb.setResult(resUser);
        }
        return rb;
    }


	//旧的版本，推荐码没有前置
	@ResponseBody
	@RequestMapping(value = "/registUser", method = RequestMethod.POST)
	public ResponseBase<SysUser> registerUser(@RequestBody UserRes res) {
		ResponseBase<SysUser> rb = new ResponseBase<>();
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("name", res.getName());

		logger.info(
				"注册registerUser MsgCode:{} , Name:{} , RecommendCode:{} , Pwd:{}",
				res.getMsgCode(), res.getName(), res.getRecommendCode(),
				res.getPwd());

		if (StringUtils.isNotEmpty(res.getMsgCode())
				&& StringUtils.isNotEmpty(res.getName())
				&& StringUtils.isNotEmpty(res.getPwd())) {

			String msgCode = RedisCilent.getString(CacheConstants.MOBLIE_MSG_CODE + res.getName());
			String company = RedisCilent.getString(CacheConstants.MOBLIE_MSG_CODE + res.getName() + "company");
			if (("YIJIA".equals(company) && (StringUtils.equalsIgnoreCase(msgCode, res.getMsgCode())))
					|| ("JIGUANG".equals(company) && (validateJG(res.getMsgCode(), res.getName(), 0)))) {// 验证码相同
				RedisCilent.delKey(CacheConstants.MOBLIE_MSG_CODE + res.getName());
				RedisCilent.delKey(CacheConstants.MOBLIE_MSG_CODE + res.getName() + "company");
				List<SysUser> list = userImpl.findByFilter(hqlFilter);
				if (list.size() == 0) {
					SysUser user = new SysUser();
					user.setName(res.getName());
					user.setPwd(res.getPwd());
					user.setMobileId(res.getMobileId());
					user.setMobileType(res.getMobileType());
					SysUser finUser = new SysUser();

					Boolean needInputCode = ifNeedInputCode();;

					logger.info("registerUser needInputCode={}", needInputCode);
					if(needInputCode) {
						String recommendCode = res.getRecommendCode();
						if (StringHelper.isEmpty(recommendCode)) {
							rb.setMsg("亲，别忘了填写推荐码哦！");
							rb.setResultCode(ResultCode.FAILED.getCode());
							logger.info("registerUser needInputCode={}, recommendCode={}", needInputCode, recommendCode);
							return rb;
						}

						finUser = userImpl.getByPhoneNum(res.getRecommendCode());
						if (finUser == null || finUser.getIsInside() == null || finUser.getIsInside() != 1) {
							rb.setMsg("没有找到这位理财师！");
							rb.setResultCode(ResultCode.FAILED.getCode());
							return rb;
						}

						logger.info("registerUser needInputCode={}, recommendCode={}, and finUser 存在", needInputCode, recommendCode);
					}
					//***************************************************************************


					if (StringUtils.isNotEmpty(res.getRecommendCode())) {
						user.setRecommendCode(res.getRecommendCode());
						user.setRecommendId(null);

						// 给用户添加渠道信息
						finUser = userImpl
								.getByPhoneNum(res.getRecommendCode());
						if (finUser != null
								&& finUser.getOrgId() != null
								&& finUser.getOrgId() != ConstantUser.USER_ORG_WUZHU) {
							user.setChannel(finUser.getChannel());
							user.setOrgId(finUser.getOrgId());
							user.setRecommendId(finUser.getId());
						} else {
							user.setChannel(getChannelWangluo());
							user.setOrgId(getDepWuzhu());

						}
					} else {
						user.setRecommendCode(null);
						user.setRecommendId(null);
						user.setChannel(getChannelWangluo());
						user.setOrgId(getDepWuzhu());
					}

					Long id = userImpl.add(user);
					SysUser resUser = null;
					if(id != null){
						resUser = userImpl.findById(id);
                        rb.setMsg("注册成功");
                        rb.setResultCode(ResultCode.SUCC.getCode());
                        rb.setResult(resUser);
					}else{
						rb.setMsg("注册失败");
						rb.setResultCode(ResultCode.FAILED.getCode());
						return rb;
					}
				} else {
					rb.setMsg("用户已存在");
					rb.setResultCode(ResultCode.USER_EXIST.getCode());
				}
			} else {
				rb.setMsg("验证码校验失败！");
				rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
			}
		} else {
			rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
		}

		logger.info("user register method end");
		return rb;
	}


	private void sendPushToFinancial(String custPhone, String finanCialphone,
			SysUser finUser) {
		if (finUser != null) {
			int isInside = finUser.getIsInside();
			if (isInside == 1 && StringHelper.isNotEmpty(custPhone)
					&& StringHelper.isNotEmpty(finanCialphone)) {// 已经是内部理财师

				String msg = ConstantPush.PUSH_REGIST_START + custPhone
						+ ConstantPush.PUSH_REGIST_END;
				pushService.jgPushMsg(msg, null, null, null, finanCialphone,
						ConstantPush.PUSH_MENU_REGISTER, MsgTypeConstants.REGISTER);
			}
		}

	}

	@ResponseBody
	@RequestMapping(value = "/reSetPwd", method = RequestMethod.POST)
	public ResponseBase<Boolean> reSetPwd(@RequestBody UserRes res) {
		ResponseBase<Boolean> rb = new ResponseBase<>();

		if (StringUtils.isNotEmpty(res.getName()) && StringUtils.isNotEmpty(res.getPwd())) {
			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addEQFilter("name", res.getName());
			hqlFilter.addEQFilter("closeAccount",0);
			List<SysUser> list = userImpl.findByFilter(hqlFilter);
			if (list.size() != 0) {
				SysUser user = list.get(0);
				user.setPwd(res.getPwd());
				userImpl.update(user);
				rb.setResult(true);
			}
		} else {
			rb.setMsg("有必填参数为空");
			rb.setResult(false);
			rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
		}
		return rb;
	}

	@ResponseBody
	@RequestMapping(value = "/checkMsgCode", method = RequestMethod.POST)
	public ResponseBase<Boolean> newResetPwd(@RequestBody UserRes res) {
		ResponseBase<Boolean> resp = new ResponseBase<>();

		if (StringUtils.isNotEmpty(res.getName()) && StringUtils.isNotEmpty(res.getMsgCode())) {
			if (validateJG(res.getMsgCode(), res.getName(), 0)) {
				resp.setResultCode(ResultCode.SUCC.getCode());
				resp.setResult(true);
			} else {
				resp.setMsg("验证码错误");
				resp.setResult(false);
				resp.setResultCode(ResultCode.FAILED.getCode());
			}

		} else {
			resp.setMsg("有必填参数为空");
			resp.setResult(false);
			resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
		}

		return resp;
	}

	/**
	 * 
	 * 从盈米得到用户的相关信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/upUserInfo", method = RequestMethod.POST)
	public ResponseBase<Boolean> upUserInfo(@RequestBody SysUserPhoneReq req) {

		String phone = req.getPhone();
		String paymentMethodId = req.getPaymentMethodId();
		String identity = req.getIdentityNo();
		String paymentNo = req.getPaymentNo();
		String accountId = req.getAccountId();

		ResponseBase<Boolean> rb = new ResponseBase<>();

		logger.info("旧版本添加绑卡信息info:  identity = " + identity + " accountId = "
				+ accountId + "  paymentNo = " + paymentNo + "    phone = "
				+ phone);
		try {
			SysUser user = userImpl.getByPhoneNum(phone);
			if (user != null) {
				HqlFilter paymentFilter = new HqlFilter();
				paymentFilter.addEQFilter("userId", user.getId());
				paymentFilter.addEQFilter("cardStatus", 1);// 已绑卡
				List<Payment> paymentList = paymentImpl
						.findByFilter(paymentFilter);
				if (paymentList.size() > 0) {
					logger.info("该用户已绑卡，不能再次绑卡！userId={}", user.getId());
					rb.setResult(false);
					rb.setMsg("该用户已绑卡，不能再次绑卡！");
					rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
					return rb;
				}

				// if (!user.getName().equals(phone)) {
				// rb.setResult(false);
				// rb.setMsg("用户银行卡留存号码与登录平台手机号码不一致，请检查手机号码！");
				// rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
				// return rb;
				// }

			} else {
				rb.setResult(false);
				rb.setMsg("该客户不存在！");
				rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
				return rb;
			}
			if (StringUtils.isNotEmpty(accountId)) {

				// 设置盈米平台账号
				user.setAccountId(accountId);

				// 设置银行卡号
				user.setPaymentNo(paymentNo);

				if (StringHelper.isNotEmpty(identity)) {
					// 设置身份证号
					user.setIdentity(identity);

					// 设置性别 男:M 0, 女 : F, 1
					Integer gender = (IdcardUtils.getGenderByIdCard(identity) == "M" ? 0
							: 1);
					user.setGender(gender);

					// 设置出生日期
					String birthdayStr = IdcardUtils.getBirthByIdCard(identity);
					SimpleDateFormat formatter = new SimpleDateFormat(
							"yyyymmdd");

					try {
						Long birthdayLong = formatter.parse(birthdayStr)
								.getTime();
						user.setBirthday(birthdayLong);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						logger.error("日期转换错误：用户在盈米平台得到身份证信息之后，转换出生日期错误！");
						e.printStackTrace();
					}
				}
				userImpl.update(user);

				// 在支付信息表里添加记录
				Payment payment = new Payment();
				payment.setUserId(user.getId());
				payment.setAccountName(user.getRealName());

				if (StringHelper.isEmpty(identity)) {// 二次绑卡补全身份证信息
					HqlFilter pFilter = new HqlFilter();
					pFilter.addEQFilter("userId", user.getId());
					List<Payment> getPayList = paymentImpl
							.findByFilter(pFilter);
					if (getPayList.size() > 0) {
						for (Payment p : getPayList) {
							String pIdentity = p.getIdentityNo();
							if (StringHelper.isNotEmpty(pIdentity)) {
								identity = pIdentity;
								break;
							} else {
								logger.info("该卡号在绑卡记录中找不到身份证信息,paymentNo={}",
										paymentNo);
							}
						}
					}
				}
				payment.setIdentityNo(identity);
				payment.setPhone(phone);
				payment.setPaymentNo(paymentNo);
				payment.setPaymentMethodId(paymentMethodId);
				payment.setCardStatus(CardStatusCode.PAYMENT_DISPLAY_SHOW);
				if (StringHelper.isNotEmpty(paymentNo)) {
					FM fm = getBankCardInfo(paymentNo);
					if (fm != null) {
						if (StringHelper.isNotEmpty(fm.getCnm())) {
							payment.setCardType(fm.getCtp());// 卡类型
							payment.setBankName(fm.getCnm());// 银行名称
							payment.setInsCard(fm.getInscd());// 银行机构号
						}
					}

				} else {
					logger.info("卡号为空！paymentNo={}", paymentNo);
				}
				paymentImpl.add(payment);
				rb.setResult(true);
				rb.setResultCode(ResultCode.SUCC.getCode());

			} else {
				logger.error("从盈米得到的信息为空！");
				rb.setResult(false);
				rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
			}
		} catch (Exception e) {
			rb.setResult(false);
			rb.setMsg("绑卡失败");
			rb.setResultCode(ResultCode.FAILED.getCode());
			logger.error("旧版本绑卡异常！");
			e.printStackTrace();
		}

		return rb;
	}

	private FM getBankCardInfo(@RequestParam String cardNum) {
		URIBuilder builder = new URIBuilder().setScheme(scheme)
				.setHost(realUrl).setPath(getBankpath);
		Map<String, String> trimmedParams = new HashMap<>();
		String MchntCd = fyMchntCd;
		String Ono = cardNum;
		String allUrl = MchntCd + "|" + Ono + "|" + fySecret;
		String Sign = MD5Crypter.md5Encrypt(allUrl);
		String fm = "<FM><MchntCd>" + MchntCd + "</MchntCd>" + "<Ono>" + Ono
				+ "</Ono>" + "<Sign>" + Sign + "</Sign></FM> ";
		trimmedParams.put("FM", fm);
		CloseableHttpResponse resp = null;
		CloseableHttpClient httpClient = null;
		try {
			URI uri = builder.build();
			RequestBuilder requestBuilder = RequestBuilder.post(uri);
			List<NameValuePair> kvs = new ArrayList<>();
			for (String key : trimmedParams.keySet()) {
				kvs.add(new BasicNameValuePair(key, trimmedParams.get(key)));
			}
			requestBuilder.setEntity(new UrlEncodedFormEntity(kvs, "UTF-8"));
			HttpUriRequest request = requestBuilder.build();

			httpClient = HttpClients.custom().setMaxConnPerRoute(200).build();

			resp = httpClient.execute(request);

			if (resp.getStatusLine().getStatusCode() >= 300) {
				System.err.println("Something wrong: "
						+ resp.getStatusLine().toString());
			}
			BufferedReader input = new BufferedReader(new InputStreamReader(
					resp.getEntity().getContent(), "UTF-8"));
			StringBuilder sb = new StringBuilder();
			char[] buf = new char[1000];
			int count;
			while ((count = input.read(buf)) > 0) {
				sb.append(buf, 0, count);
			}
			logger.info("查询该银行卡号信息如下：Ono={},sb={}", Ono, sb.toString());
			// System.out.println(sb.toString());
			String result = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
					+ sb.toString().toLowerCase();
			BeanAndXMLTurn<FM> ff = new BeanAndXMLTurn<FM>();
			FM fmresultFm = ff.XMLStringToBean(result, new FM());

			return fmresultFm;
		} catch (IOException | URISyntaxException e) {
			logger.error("fyValidate()方法异常！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (resp != null) {
					resp.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				logger.error("获取卡信息异常");
				e.printStackTrace();

			}
		}
	}

	@ResponseBody
	@RequestMapping(value = "/getDetailInfo", method = RequestMethod.POST)
	public String getDetailInfo(@RequestBody UserRes res) {
		String resultStr = null;
		String url = "/account/getAccount";
		Map<String, String> params = new HashMap<>();

		params.put("brokerUserId", res.getName());

		params.put("accountId", res.getAccountId());

		resultStr = utils.get(url, params);

		return resultStr;
	}

	@ResponseBody
	@RequestMapping(value = "/getIdentity")
	public ResponseBase getIdentity(@RequestParam Long userId) {
		ResponseBase responseBase = new ResponseBase();
		SysUser sysUser = this.userImpl.findById(userId);
		if (sysUser != null) {
			responseBase.setResult(sysUser.getIdentity());
		}
		responseBase.setResultCode(ResultCode.SUCC.getCode());
		responseBase.setMsg("success");
		return responseBase;
	}



	/**
	 * 该方法用于当用户填写推荐码之后，给用户赠送加息券
	 * 
	 * @param userId
	 */
	private void addUserCardByUserId(Long userId) {
		SysUser user = userImpl.findById(userId);
		if(user == null){
			return;
		}

		//赠送体验金
		logger.info("给用户赠送体验金 userId={}", userId);
		
		couponService.sendTYJToUser(userId);

		// 01 如果用户不存在，或推荐码为空，则直接退出
		if (StringHelper.isEmpty(user.getRecommendCode())) {
			logger.info("推荐码为空将不送加息券 userId={}", userId);
			return;
		}

		// 02 如果填的推荐码不是正确的理财师，则直接退出
		SysUser finUser = userImpl.getByPhoneNum(user.getRecommendCode());

		if (finUser.getIsInside() != 1) {
			logger.info("推荐理财未注册， 空将不送加息券 userId={}， finUser.getIsInside={}", userId, finUser.getIsInside());
			return;
		}

		// 03 给用添加卡券
		logger.info("给用户赠送加息券 userId={}", userId);
		couponService.sendJXQToUser(userId);
	}

	//校验验证码
	private CheckInfo checkMsgCode(String phoneNum, String inputCode) {
		CheckInfo checkInfo = new CheckInfo();
		checkInfo.setResult(false);
		checkInfo.setResultMsg("验证码校验失败！");

		if (StringHelper.isEmpty(phoneNum) || StringHelper.isEmpty(inputCode)) {
			return checkInfo;
		}


		String msgCode = RedisCilent.getString(CacheConstants.MOBLIE_MSG_CODE + phoneNum);
		String company = RedisCilent.getString(CacheConstants.MOBLIE_MSG_CODE + phoneNum + "company");


		if (("YIJIA".equals(company) && (StringUtils.equalsIgnoreCase(msgCode, inputCode)))
				|| ("JIGUANG".equals(company) && (validateJG(inputCode, phoneNum, 0)))) {// 验证码相同
			RedisCilent.delKey(CacheConstants.MOBLIE_MSG_CODE + phoneNum);
			RedisCilent.delKey(CacheConstants.MOBLIE_MSG_CODE + phoneNum + "company");
			checkInfo.setResult(true);
			checkInfo.setResultMsg("验证码校验成功");
		}

		return checkInfo;
	}

	//是否需要封闭注册
	private Boolean ifNeedInputCode(){
		Boolean needInputCode = false;
		Parameter parm = parmService.getByName(ConstantParm.REGIST_CODE_LIMIT);

		if (parm != null && StringHelper.isNotEmpty(parm.getValue01()) && StringHelper.isNotEmpty(parm.getValue02()) && StringHelper.isNotEmpty(parm.getValue03())) {
			Long startTime = DateHelper.stringToDate(parm.getValue02()).getTime();

			Long endTime = DateHelper.stringToDate(parm.getValue03()).getTime();

			Long currentTime = System.currentTimeMillis();

			if (parm.getValue01().equals("1") && startTime.compareTo(currentTime) == -1 && endTime.compareTo(currentTime) == 1) {
				logger.info("用户注册必须填推荐码！");
				needInputCode = true;
			}
		}
		return needInputCode;
	}

	/**
	 *
	 * APP应用登录 -- 新加手势密码字段
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/app/login", method = RequestMethod.POST)
	public ResponseBase<AppGestureCipherRes> appLogin(@RequestBody UserRes req) {
		logger.info("/app/login ---> userName:{} , msgCode:{}", req.getName(), req.getMsgCode());

		ResponseBase<AppGestureCipherRes> rb = new ResponseBase<>();
		AppGestureCipherRes sresp = new AppGestureCipherRes();

		//手势密码 1 硬编码保存到表
		String requestStr = webUrl + "/api/userinfo/getCipherState?loginName="+ req.getName() +"&appType=1";
		ResponseEntity<String> forEntity = template.getForEntity(requestStr, String.class);
		if(forEntity.toString().contains("\"resultCode\":\"1001\"")) {
			sresp.setGestureCipher(null);
		}else {
			GetCipherStateRes forObject = template.getForObject(requestStr, GetCipherStateRes.class);
			//手势密码
			String gestureCipher = forObject.getResult().getGestureCipher();
			//设置手势密码
			sresp.setGestureCipher(gestureCipher);
		}

		String phoneWhiteList = "13556806196,18902212310";
		HqlFilter hqlFilter = new HqlFilter();
		if (StringUtils.isNotEmpty(req.getName())) {
			String msgCode = RedisCilent
					.getString(CacheConstants.MOBLIE_MSG_CODE + req.getName());
			String company = RedisCilent
					.getString(CacheConstants.MOBLIE_MSG_CODE + req.getName()
							+ "company");
			hqlFilter.addEQFilter("name", req.getName().trim());
			hqlFilter.addEQFilter("closeAccount",0); //只有末销户的用户才能登录-2.7.6

			List<SysUser> list = userImpl.findByFilter(hqlFilter);

			if (list.size() == 0) {
				logger.info("login 此用户不存在 name = {} ",req.getName());
				rb.setMsg("此用户不存在");
				rb.setResultCode(ResultCode.USER_NOT_EXIST.getCode());
				return rb;
			}

			SysUser loginUser = list.get(0);

			// add by Sam 2016/07/22 增加token
			switch (req.getLoginType()) {
				case 1:// 验证码登陆
					if (StringUtils.isNotEmpty(req.getMsgCode())) {
						if (phoneWhiteList.contains(req.getName())
								|| ("YIJIA".equals(company) && (StringUtils
								.equalsIgnoreCase(msgCode, req.getMsgCode())))
								|| ("JIGUANG".equals(company) && (validateJG(
								req.getMsgCode(), req.getName(), 0)))) {
							ReqToModelHelper.copyReqValueToModel(loginUser, sresp);
							String token = RandomStringUtils.randomAlphanumeric(64);
							sresp.setToken(token);
							RedisCilent.setString(CacheConstants.UserLog_Token
									+ loginUser.getId(), token, 604800);
							// 短信验证登录成功
							// 短信验证登录如果成功，且mobileId 不相同时，更改用户的mobileId
							if (StringHelper.isEmpty(loginUser.getMobileId())
									|| (!loginUser.getMobileId().equals(
									req.getMobileId()))) {
								if (StringHelper
										.isNotEmpty(loginUser.getMobileId())) {
									Answer an = answerService
											.getByMobileId(loginUser.getMobileId());
									if (an != null) {
										an.setMobileId(req.getMobileId());
										answerService.update(an);
									}
								}
								loginUser.setMobileId(req.getMobileId());
								userImpl.update(loginUser);
								Answer nowMobileAnswer = answerService
										.getByMobileId(req.getMobileId());
								if (nowMobileAnswer != null) {
									answerService.delete(nowMobileAnswer.getId());
								}
							}
							sresp.setMobileId(req.getMobileId());

							rb.setResult(sresp);
							RedisCilent.delKey(CacheConstants.MOBLIE_MSG_CODE
									+ req.getName() + "company");
							RedisCilent.delKey(CacheConstants.MOBLIE_MSG_CODE
									+ req.getName());
						} else {
							logger.info("login 验证码错误 name={},msgCode={}",req.getName(),req.getMsgCode());
							rb.setMsg("验证码错误，请输入正确的验证码.");
							rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
						}
					} else {
						rb.setMsg("验证码不能为空，请输入正确的验证码.");
						rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
					}

					break;

				case 2:// 密码登陆
					if (list.get(0).getPwd().equalsIgnoreCase(req.getPwd())) {// 密码登陆如果换手机了，在新手机上第一次都要验证码登陆。更安全，发送到你自己的手机
						// 此时账户和密码相同,再判断UUID 是否相同
						// SysUser loginUser = list.get(0);
						// 如果手机唯一识别码和数据库中用户的唯一识别码相同
						ReqToModelHelper.copyReqValueToModel(loginUser, sresp);
						String token = RandomStringUtils.randomAlphanumeric(64);

						if (StringHelper.isNotEmpty(loginUser.getMobileId())
								&& StringHelper.isNotEmpty(loginUser.getMobileId())
								&& loginUser.getMobileId()
								.equals(req.getMobileId())) {
							sresp.setToken(token);
							RedisCilent.setString(CacheConstants.UserLog_Token
									+ loginUser.getId(), token, 604800);
							rb.setResult(sresp);
							// 判断是否是测试员
						} else if (req.getName().equalsIgnoreCase("13411112222")
								|| req.getName().equalsIgnoreCase("18988888888")) {
							sresp.setToken(token);
							RedisCilent.setString(CacheConstants.UserLog_Token
									+ loginUser.getId(), token, 604800);
							rb.setResult(sresp);
							logger.info("The login user is the tester, and will login succ.");
						} else {
							rb.setMsg(ResultCode.PHONE_CHANGE.getMsg());
							rb.setResultCode(ResultCode.PHONE_CHANGE.getCode());
						}

					} else {
						logger.info("login 账号或密码错误 name={}",req.getName());
						rb.setMsg("账号或密码错误，请重新输入.");
						rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
					}
					break;
			}

		} else {
			logger.info("login 用户名与密码有空");
			rb.setMsg("用户名与密码不能为空，请重新输入.");
			rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
		}
		// logger.info("adhfjsf{}", new JSONObject(rb));
		return rb;

	}

    private int getChannelWangluo() {
        Parameter param = getNoOrgAndChannelConfig();

        if(param == null)
        {
            return ConstantOrg.CHANNEL_WANGLUO;
        }

        Integer result = Integer.valueOf(param.getValue01());
        return result;
    }

    private int getDepWuzhu() {
        Parameter param = getNoOrgAndChannelConfig();

        if(param == null)
        {
            return ConstantOrg.DEP_WUZHU;
        }

        Integer result = Integer.valueOf(param.getValue02());
        return result;
    }

    private Parameter getNoOrgAndChannelConfig(){
        Parameter param = parmService.getByName(ConstantParm.DEFAULT_NO_ORG_AND_CHANNEL);

        return param;
    }
}
